package com.lagou.edu.mvcframework.factory;

import com.lagou.edu.mvcframework.annotations.Security;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class SecurityProxyFactory {

    public static Object getJdkProxy(Object o){
        if(null == o){
            throw new IllegalArgumentException();
        }

        return Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if(method.isAnnotationPresent(Security.class)){
                    Security security = method.getAnnotation(Security.class);
                    String[] value = security.value();
                    if(value.length == 0){
                        throw new IllegalAccessException("无权限访问");
                    }
                    boolean hasName = false;
                    for (String s : value) {
                        for (Object arg : args) {
                            if(s.equals(arg)){
                                hasName = true;
                                break;
                            }
                        }
                    }

                    if(!hasName){
                        throw new IllegalAccessException("无权限访问");
                    }
                }

                return method.invoke(proxy, args);
            }
        });
    }

}
